Popular Searches
Popular Course Categories
Popular Courses

Parsing JSON Responses and Managing API Data

Parsing JSON Responses and Managing API Data

API Integration and Network Requests

Parsing JSON Responses and Managing API Data in React Native

Course: React Native Training

Topic: Parsing JSON Responses and Managing API Data

Course Link: React Native Training Course

Demo Link: Register for a Free Course Demo

Website: JustAcademy


1. Introduction to JSON and API Data

Modern React Native applications frequently communicate with remote servers to retrieve user profiles, product lists, articles, orders, weather information, and other dynamic content. APIs commonly return data in JSON (JavaScript Object Notation) format. React Native applications must receive this response, parse it, validate the data, handle errors, and store the resulting information in state so it can be displayed in the user interface.

Parsing JSON and managing API data are important skills because applications must handle both successful and unsuccessful requests while remaining responsive and reliable.

Learning Objectives

  • Understand JSON syntax and structure.
  • Learn how APIs return JSON responses.
  • Parse JSON responses using Fetch and Axios.
  • Understand objects, arrays, nested objects, and arrays of objects.
  • Manage API data using React Native state.
  • Handle loading, empty, success, and error states.
  • Validate API response data before using it.
  • Implement pagination, refreshing, filtering, and searching.
  • Prevent common data-handling errors.

2. What Is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight text-based format used to exchange structured data between applications and servers. JSON is language-independent, although its syntax resembles JavaScript objects.

Example of JSON Data

{
  "id": 101,
  "name": "Rahul Sharma",
  "email": "[email protected]",
  "isActive": true
}

The example represents one user with an ID, name, email address, and active status.

Common JSON Data Types

Data Type Example Description
String "React Native" Text enclosed in double quotation marks.
Number 25 An integer or decimal number.
Boolean true or false A logical value.
Object {"name":"Rahul"} A collection of key-value pairs.
Array [10,20,30] An ordered collection of values.
Null null An explicitly empty or absent value.

Important JSON Rules

  • Property names and string values use double quotation marks.
  • Properties are separated by commas.
  • JSON does not support comments.
  • JSON does not support JavaScript functions or undefined values.
  • Trailing commas are not valid in standard JSON.
  • JSON objects and arrays can be nested.

3. Understanding API Responses

An API response is the information returned by a server after a client sends an HTTP request. A response normally includes an HTTP status code, response headers, and an optional response body.

Example API Response Body

{
  "success": true,
  "message": "Users retrieved successfully",
  "data": [
    {
      "id": 1,
      "name": "Aarav",
      "email": "[email protected]"
    },
    {
      "id": 2,
      "name": "Priya",
      "email": "[email protected]"
    }
  ]
}

In this example, the response contains a success indicator, a message, and a data array containing two users.

Common HTTP Status Codes

Status Code Meaning Typical Handling
200 OK Process the successful response.
201 Created Handle a successfully created resource.
204 No Content Handle success without expecting a response body.
400 Bad Request Check the request data and parameters.
401 Unauthorized Check authentication credentials.
403 Forbidden Check permissions.
404 Not Found Check the endpoint or requested resource.
429 Too Many Requests Respect rate limits and retry guidance.
500 Internal Server Error Handle the server failure gracefully.

Important: A successful HTTP status does not always guarantee that the response contains the expected application data. Validate the response structure before using it.

4. Parsing JSON Using the Fetch API

The Fetch API is built into React Native and can be used to send HTTP requests. When a server returns JSON, call the response's json() method to read and parse the response body.

Basic Fetch Example

const fetchUser = async () => {
  try {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/users/1"
    );

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const user = await response.json();

    console.log(user.name);
    console.log(user.email);
  } catch (error) {
    console.error("Unable to fetch user:", error.message);
  }
};

Explanation

  1. fetch() sends the request to the API endpoint.
  2. await waits for the HTTP response.
  3. response.ok checks whether the HTTP status is in the successful range.
  4. response.json() reads the body and parses JSON into JavaScript values.
  5. The parsed user object can then be accessed using its properties.
  6. The catch block handles network errors and errors thrown during processing.

Note: Fetch generally does not reject its promise just because the server returns an HTTP error status such as 404 or 500. Check response.ok or response.status explicitly.

5. Parsing JSON Using Axios

Axios is a popular HTTP client library. When a response contains JSON, Axios usually parses it automatically and makes the resulting data available through response.data.

Install Axios

npm install axios

Basic Axios Example

import axios from "axios";

const fetchUser = async () => {
  try {
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/users/1"
    );

    const user = response.data;

    console.log(user.name);
    console.log(user.email);
  } catch (error) {
    console.error("Unable to fetch user:", error.message);
  }
};

Fetch vs Axios JSON Handling

Feature Fetch Axios
Request fetch(url) axios.get(url)
JSON parsing Usually call response.json() JSON is usually parsed automatically.
Response body Parsed value returned by response.json() response.data
HTTP error statuses Check response.ok Rejected by default for non-2xx statuses.
Configuration Built-in request options Convenient defaults, instances, and interceptors.

6. Working with JSON Objects

A JSON object contains key-value pairs. Once parsed, the object can be accessed using dot notation or bracket notation.

Example

const user = {
  id: 10,
  name: "Neha",
  email: "[email protected]",
  address: {
    city: "Mumbai",
    country: "India"
  }
};

console.log(user.name);
console.log(user["email"]);
console.log(user.address.city);

Output:

Neha
[email protected]
Mumbai

When to Use Dot and Bracket Notation

  • Use dot notation when the property name is known, such as user.name.
  • Use bracket notation when the property name is stored in a variable, such as user[fieldName].
  • Use optional chaining for properties that may be missing, such as user.address?.city.

7. Working with Arrays of Objects

Many APIs return collections of objects. For example, a product API may return an array containing product IDs, names, prices, and descriptions. You can use array methods to process the returned information.

Example Product Data

const products = [
  { id: 1, name: "Keyboard", price: 1200 },
  { id: 2, name: "Mouse", price: 500 },
  { id: 3, name: "Monitor", price: 8500 }
];

const productNames = products.map(product => product.name);
const affordableProducts = products.filter(
  product => product.price < 2000
);

console.log(productNames);
console.log(affordableProducts);

Useful Array Methods

Method Purpose Example
map() Transforms every item into a new value. users.map(user => user.name)
filter() Returns items that satisfy a condition. products.filter(p => p.price < 1000)
find() Returns the first matching item. users.find(user => user.id === 2)
some() Checks whether at least one item matches. users.some(user => user.active)
reduce() Combines items into a single result. prices.reduce((sum, price) => sum + price, 0)

8. Understanding Nested JSON Data

APIs often return nested structures in which objects contain other objects or arrays. You must understand the structure to access the correct properties safely.

Example Nested Response

{
  "id": 501,
  "title": "React Native Basics",
  "author": {
    "id": 12,
    "name": "Ananya"
  },
  "tags": ["React Native", "JavaScript", "Mobile"]
}

Accessing Nested Properties

const article = {
  id: 501,
  title: "React Native Basics",
  author: {
    id: 12,
    name: "Ananya"
  },
  tags: ["React Native", "JavaScript", "Mobile"]
};

console.log(article.author.name);
console.log(article.tags[0]);

Use optional chaining when nested properties may not exist:

const authorName = article.author?.name ?? "Unknown author";

Optional chaining prevents an error when an intermediate property is null or undefined. The nullish coalescing operator (??) supplies a fallback when the value is nullish.

9. Managing API Data with React State

React Native uses React state to store data that affects what appears on the screen. The useState hook is commonly used for API results, loading indicators, error messages, and user interactions.

Example State Variables

import React, { useState } from "react";

const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
  • users stores the parsed user records.
  • loading indicates whether a request is in progress.
  • error stores an error message when the request fails.

Always update state through its setter function. Do not mutate existing arrays or objects directly.

Incorrect State Mutation

// Incorrect: directly mutates the existing array
users.push(newUser);

Correct State Update

// Correct: creates a new array
setUsers(previousUsers => [...previousUsers, newUser]);

Creating new arrays and objects helps React detect updates and render the latest data.

10. Fetching and Displaying API Data in React Native

The following example demonstrates a complete screen that retrieves users, parses the JSON response, stores the result in state, and displays the records using FlatList.

Complete Example Using Fetch

import React, { useEffect, useState } from "react";
import {
  ActivityIndicator,
  FlatList,
  SafeAreaView,
  Text,
  View,
  StyleSheet
} from "react-native";

export default function UsersScreen() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const controller = new AbortController();

    const loadUsers = async () => {
      try {
        setLoading(true);
        setError("");

        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users",
          { signal: controller.signal }
        );

        if (!response.ok) {
          throw new Error(`Request failed: ${response.status}`);
        }

        const result = await response.json();

        if (!Array.isArray(result)) {
          throw new Error("Unexpected API response format.");
        }

        setUsers(result);
      } catch (err) {
        if (err.name !== "AbortError") {
          setError(err.message || "Something went wrong.");
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    };

    loadUsers();

    return () => controller.abort();
  }, []);

  if (loading) {
    return (
      
        
        Loading users...
      
    );
  }

  if (error) {
    return (
      
        {error}
      
    );
  }

  if (users.length === 0) {
    return (
      
        No users found.
      
    );
  }

  return (
    
      
            {item.name}
            {item.email}
            {item.phone}
          
        )}
      />
    
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16
  },
  center: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    padding: 20
  },
  card: {
    padding: 14,
    marginBottom: 10,
    borderWidth: 1,
    borderColor: "#dddddd",
    borderRadius: 8
  },
  name: {
    fontSize: 18,
    fontWeight: "bold"
  }
});

How the Example Works

  1. useState stores the users, loading status, and error message.
  2. useEffect starts the API request when the screen component mounts.
  3. fetch() sends the request and receives the HTTP response.
  4. response.ok checks whether the request succeeded.
  5. response.json() parses the response body.
  6. Array.isArray() verifies that the returned data is an array.
  7. setUsers() updates the component state.
  8. FlatList renders the records efficiently.
  9. The abort controller cancels the request during cleanup when supported by the runtime.

11. Managing Loading, Success, Empty, and Error States

API-driven screens should account for different request outcomes. A well-designed interface communicates what is happening instead of displaying a blank screen when data is unavailable.

State Meaning Suggested UI
Loading The request is in progress. Activity indicator and loading message.
Success Valid data has been received. Display the data.
Empty The request succeeded but returned no records. Show a helpful empty-state message.
Error The request or processing failed. Show a clear error message and retry option.

Example of State-Based Rendering

if (loading) {
  return <Text>Loading...</Text>;
}

if (error) {
  return <Text>Unable to load data: {error}</Text>;
}

if (items.length === 0) {
  return <Text>No items available.</Text>;
}

return <Text>Items loaded: {items.length}</Text>;

In a complete screen, these conditions should be arranged so the UI renders the correct state at the right time. A retry button can call the same data-loading function again.

12. Validating and Normalizing API Data

Never assume every API response has the expected structure. APIs can change, fields can be missing, and values can be null. Validate data before rendering or using it in calculations.

Basic Validation

function normalizeUser(user) {
  if (!user || typeof user !== "object") {
    return null;
  }

  if (typeof user.id !== "number") {
    return null;
  }

  return {
    id: user.id,
    name: typeof user.name === "string"
      ? user.name
      : "Unknown user",
    email: typeof user.email === "string"
      ? user.email
      : ""
  };
}

const validUsers = apiUsers
  .map(normalizeUser)
  .filter(Boolean);

This example removes records without a valid numeric ID and supplies safe defaults for optional text fields. Real APIs may use string IDs, so validation rules must match the actual API contract.

Common Validation Techniques

  • Check whether the response is an object or array as expected.
  • Verify required fields such as identifiers.
  • Check the data types of names, prices, dates, and status fields.
  • Handle missing and null properties.
  • Normalize inconsistent formats into a predictable structure.
  • Use schema-validation libraries for complex responses when appropriate.

13. Handling Missing Values and Optional Properties

API fields may be absent, undefined, or explicitly null. Directly accessing a nested property without checking it can cause runtime errors.

Unsafe Access

const city = user.address.city;

This can fail if address is null or missing.

Safe Access

const city = user.address?.city ?? "City not provided";

Use || carefully. It treats empty strings, zero, and false as fallback-worthy values. Use ?? when only null and undefined should trigger the fallback.

const quantity = product.quantity ?? 0;
const displayName = user.name?.trim() || "Unnamed user";

14. Transforming and Filtering API Data

Sometimes the raw API response is not suitable for direct display. You may need to filter, sort, or transform records before rendering them.

Filtering Products by Price

const affordableProducts = products.filter(
  product => product.price <= 2000
);

Sorting Products by Price

const sortedProducts = [...products].sort(
  (a, b) => a.price - b.price
);

The spread operator creates a copy before sorting, preventing the original array from being mutated.

Formatting Data for Display

const displayProducts = products.map(product => ({
  id: product.id,
  title: product.title ?? "Untitled product",
  formattedPrice: `₹${Number(product.price).toFixed(2)}`
}));

Ensure values are validated before conversion. For currency calculations, consider using integer minor units or a suitable decimal-handling strategy when financial precision is important.

15. Updating API Data After User Actions

When users add, edit, or delete information, the screen must reflect the changes. Depending on the application, you can update local state optimistically or fetch the latest data from the server.

Adding an Item to State

const addProduct = newProduct => {
  setProducts(previous => [
    ...previous,
    newProduct
  ]);
};

Updating an Existing Item

const updateProduct = updatedProduct => {
  setProducts(previous =>
    previous.map(product =>
      product.id === updatedProduct.id
        ? { ...product, ...updatedProduct }
        : product
    )
  );
};

Deleting an Item

const deleteProduct = productId => {
  setProducts(previous =>
    previous.filter(product => product.id !== productId)
  );
};

These examples update local UI state. In a real application, send the appropriate API request and handle failure before treating the server-side change as permanent. If the request fails, restore the previous state or refresh the data as needed.

16. Refreshing API Data

Mobile applications often provide pull-to-refresh so users can request the latest information. React Native's FlatList supports this using refreshing and onRefresh.

Example

<FlatList
  data={users}
  keyExtractor={item => String(item.id)}
  renderItem={({ item }) => (
    <Text>{item.name}</Text>
  )}
  refreshing={refreshing}
  onRefresh={loadUsers}
/>

Define refreshing using state and ensure loadUsers sets it to true before the request and false in a finally block. A reusable loading function makes initial loading and manual refresh easier to manage.

17. Pagination and Large API Responses

Some APIs return hundreds or thousands of records. Loading all records at once can increase response time, memory usage, and rendering costs. Pagination retrieves data in smaller batches.

Common Pagination Parameters

Parameter Meaning Example
page Requested page number. page=2
limit Maximum number of records. limit=20
offset Number of records to skip. offset=20
cursor Token identifying the next position. API-specific token.

Example Request with Query Parameters

const response = await fetch(
  "https://example.com/api/products?page=1&limit=20"
);

if (!response.ok) {
  throw new Error(`HTTP error: ${response.status}`);
}

const result = await response.json();

The endpoint and pagination format depend on the API. Some APIs return an array directly; others return an object with fields such as items, total, and nextCursor.

18. Searching API Data

Searching lets users find specific records. If the API returns a manageable collection, local filtering may be sufficient. For large collections, server-side searching is usually more efficient.

Local Search Example

const filteredUsers = users.filter(user =>
  user.name
    .toLowerCase()
    .includes(searchText.toLowerCase())
);

Server-Side Search Example

const response = await fetch(
  `https://example.com/api/users?search=${encodeURIComponent(searchText)}`
);

if (!response.ok) {
  throw new Error(`HTTP error: ${response.status}`);
}

const result = await response.json();

Use encodeURIComponent() to safely encode search text in a URL parameter. For rapidly changing search input, consider debouncing requests, cancelling outdated requests, and ignoring stale results so older responses do not overwrite newer searches.

19. Managing API Data with a Service Layer

As an application grows, keeping request logic inside every screen makes the code difficult to maintain. A service layer separates API communication from UI rendering.

Example Project Structure

src/
  services/
    userService.js
  screens/
    UsersScreen.js
  components/
    UserCard.js

User Service Example

// src/services/userService.js

const BASE_URL = "https://jsonplaceholder.typicode.com";

export async function getUsers() {
  const response = await fetch(`${BASE_URL}/users`);

  if (!response.ok) {
    throw new Error(`Unable to load users (${response.status})`);
  }

  const data = await response.json();

  if (!Array.isArray(data)) {
    throw new Error("Invalid users response.");
  }

  return data;
}

Using the Service in a Screen

import { getUsers } from "../services/userService";

const loadUsers = async () => {
  try {
    setLoading(true);
    setError("");

    const data = await getUsers();
    setUsers(data);
  } catch (err) {
    setError(err.message || "Unable to load users.");
  } finally {
    setLoading(false);
  }
};

In a production application, also consider cancellation, timeouts, authentication, consistent error handling, response validation, and retry policies where appropriate.

20. Handling Network and Parsing Errors

Several different problems can occur during API communication. Distinguishing them helps developers debug issues and provide useful feedback to users.

Error Type Possible Cause Recommended Handling
Network error No connection, DNS failure, or server unreachable. Show a connection message and allow retry.
HTTP error Server returns 400, 404, 500, or another unsuccessful status. Check status and handle the response appropriately.
JSON parsing error Response body is not valid JSON. Verify the endpoint and response content type.
Structure error Expected array or object is missing. Validate the data structure.
Missing property Optional field is absent or null. Use validation, optional chaining, and sensible defaults.
Timeout Request takes too long. Configure a timeout or cancellation strategy.
Stale response An older request finishes after a newer request. Cancel outdated requests or track request identifiers.

Handling JSON Parsing Errors

try {
  const response = await fetch(apiUrl);

  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error("Request or parsing failed:", error.message);
}

For debugging, inspect the API endpoint, response status, response headers, and actual response body. Do not assume that every endpoint returns JSON; some endpoints return empty bodies, HTML error pages, or plain text.

21. Handling Empty and Non-JSON Responses

Some endpoints return no body, especially with HTTP 204 responses. Calling response.json() on an empty body can cause a parsing error.

Handling a No-Content Response

const response = await fetch(apiUrl, {
  method: "DELETE"
});

if (!response.ok) {
  throw new Error(`HTTP error: ${response.status}`);
}

if (response.status === 204) {
  // Request succeeded; there is no response body.
  return null;
}

const contentType = response.headers.get("content-type") || "";

if (contentType.includes("application/json")) {
  return await response.json();
}

return await response.text();

Use this approach only when the endpoint may legitimately return different response formats. For a known JSON-only API, keep the parsing logic simpler and validate its documented response contract.

22. Security Best Practices for API Data

  • Do not store passwords, private keys, or confidential credentials in source code.
  • Use HTTPS for API communication.
  • Keep sensitive server secrets on the server rather than inside a mobile app.
  • Use secure token storage appropriate to the sensitivity of the credentials.
  • Validate user input and API response data.
  • Never assume data returned by a server is safe to use without validation.
  • Avoid logging access tokens, personal information, or confidential response bodies.
  • Use authorization checks on the server; hiding UI elements is not a security boundary.
  • Handle authentication failures and expired sessions appropriately.
  • Follow privacy requirements when caching or retaining user information.

23. Performance Best Practices

  • Use FlatList for long lists instead of rendering every item inside a regular ScrollView.
  • Fetch only the fields and records needed by the screen when the API supports it.
  • Use pagination or cursor-based loading for large datasets.
  • Avoid sending duplicate requests unnecessarily.
  • Cancel requests that are no longer relevant when supported.
  • Use caching when appropriate, with a clear freshness and invalidation strategy.
  • Keep expensive transformations out of frequently repeated render paths when possible.
  • Use stable keys such as record IDs when rendering lists.
  • Provide loading indicators and responsive error handling.
  • Measure performance before adding complex optimizations.

24. Common Mistakes and Their Solutions

Mistake Why It Is a Problem Solution
Forgetting await response.json() The code may use a promise instead of parsed data. Await the parsing operation.
Using response.data with Fetch Fetch does not use Axios's response structure. Use the value returned by response.json().
Using response.json() with Axios Axios generally parses JSON automatically. Read response.data.
Not checking HTTP status Fetch may resolve even when the server returns an error status. Check response.ok.
Assuming every response is an array The API may return an object or another format. Validate the response structure.
Mutating state directly React may not detect the expected update. Create a new array or object and use the setter.
Not handling loading state Users may see a blank or confusing screen. Display an appropriate loading indicator.
Rendering missing nested values Property access can throw an error. Use validation and optional chaining.
Ignoring request cleanup Outdated requests can waste resources or cause stale updates. Use cancellation or request tracking where appropriate.
Using array indexes as list keys List updates may render incorrectly when items change order. Use stable unique identifiers.

25. Practical Project: User Directory App

Project Goal: Build a React Native screen that retrieves users from an API, parses the JSON response, displays user information, and handles loading, error, empty, and refresh states.

Project Requirements

  1. Create a React Native project.
  2. Create a UsersScreen component.
  3. Fetch user records from a test API such as JSONPlaceholder Users API.
  4. Check the HTTP response status.
  5. Parse the response body using response.json().
  6. Validate that the response is an array.
  7. Store users in React state.
  8. Display each user's name, email, and phone number using FlatList.
  9. Show a loading indicator while fetching records.
  10. Show an error message when the request fails.
  11. Show an empty-state message when no users are available.
  12. Add a retry button or pull-to-refresh functionality.
  13. Add a search field to filter users by name.
  14. Test the screen with invalid, empty, and successful responses.

Expected Result

The application displays a list of users after the API request succeeds. While data is being retrieved, a loading indicator appears. If the request fails, the user sees a clear error message. If the API returns no records, the screen displays an empty-state message. Search and refresh controls help users interact with the data.

26. Practice Exercises

  1. Create a JSON object containing a student's name, age, course, and enrollment status.
  2. Fetch a single user from a test API and display the user's name.
  3. Fetch an array of products and render the products with FlatList.
  4. Display a fallback message when an API field is missing.
  5. Filter an array of products by price.
  6. Sort a list of users alphabetically by name.
  7. Add loading and error states to an API-driven screen.
  8. Handle an API response that contains an empty array.
  9. Handle a 404 response without crashing the application.
  10. Build a search field that filters the data by name.
  11. Implement a refresh action that reloads the data.
  12. Move the request logic into a separate service file.

27. Interview Questions and Answers

Q1. What is JSON?

Answer: JSON is a text-based format for representing structured data using objects, arrays, strings, numbers, booleans, and null values.

Q2. How do you parse JSON in React Native?

Answer: With Fetch, call and await response.json(). With Axios, JSON responses are usually parsed automatically and accessed through response.data.

Q3. What is the difference between JSON and a JavaScript object?

Answer: JSON is a text format with strict syntax rules. A JavaScript object is a runtime data structure that can contain values and features not supported by JSON.

Q4. Why should you check response.ok when using Fetch?

Answer: Fetch does not automatically reject a request solely because the server returns an HTTP error status. Checking response.ok allows the application to handle unsuccessful HTTP responses explicitly.

Q5. What does response.json() do?

Answer: It reads the response body and parses the JSON text into JavaScript values. It returns a promise, so it should normally be awaited.

Q6. How do you manage API data in React Native?

Answer: Use React state for data that affects the screen. A component can maintain separate state variables for the API results, loading status, and errors.

Q7. What is the purpose of useEffect in API fetching?

Answer: It can run a data-fetching operation when a component mounts or when specified dependencies change. Cleanup can cancel or invalidate outdated requests.

Q8. What is the purpose of FlatList?

Answer: FlatList renders long lists efficiently by rendering items as needed rather than rendering every item at once.

Q9. What is optional chaining?

Answer: Optional chaining, written as ?., safely accesses nested properties when an intermediate value may be null or undefined.

Q10. How do you handle an empty API response?

Answer: Check whether the parsed collection is empty and display a useful empty-state message instead of leaving the screen blank.

Q11. What is the difference between map() and filter()?

Answer: map() transforms each element and returns a new array. filter() returns a new array containing only elements that satisfy a condition.

Q12. Why should state not be mutated directly?

Answer: Direct mutation can prevent React from recognizing the intended update. Use state setters with new arrays or objects.

Q13. How can you prevent stale API responses from overwriting newer results?

Answer: Cancel outdated requests when possible or track request identifiers and ignore results from requests that are no longer current.

Q14. What is API response validation?

Answer: It checks that the received data has the expected structure, required fields, and appropriate types before the application uses it.

Q15. Why is pagination useful?

Answer: Pagination reduces the amount of data transferred and processed at one time, improving responsiveness for large collections.

28. Quick Revision Checklist

  • JSON represents structured data in a text format.
  • JSON supports objects, arrays, strings, numbers, booleans, and null.
  • Fetch uses response.json() to parse JSON responses.
  • Axios generally exposes parsed response data through response.data.
  • Fetch requests require explicit HTTP status checking.
  • React state stores data that affects the UI.
  • Loading, success, empty, and error states should be handled separately.
  • Validate API response shapes before rendering.
  • Use optional chaining for potentially missing nested properties.
  • Use immutable state updates with arrays and objects.
  • Use FlatList for long collections.
  • Consider pagination, refresh, cancellation, and caching when appropriate.
  • Keep API logic in service modules as projects grow.
  • Never expose private credentials or sensitive response data in logs.

29. Conclusion

Parsing JSON responses and managing API data are essential parts of React Native development. By understanding JSON structures, checking HTTP responses, parsing data correctly, validating fields, and managing React state, developers can build reliable and responsive mobile applications.

Combining these techniques with loading indicators, error handling, pagination, refresh controls, and a reusable service layer helps make API-driven applications easier to maintain and scale.

30. Useful Resources

whatsapp